const util = require("../../../../utils/util")
const screencustomerservice = require("../../../../apiservice/screen/screencustomerservice");
const configData = require("./config");
const userinfo = wx.getStorageSync('useridentity');
const scResult = require('../add/getscresult.js');
const helper = require('./helper.js');
var modifybehavior = require('modifybehavior')
const app = getApp();
const regeneratorRuntime = app.globalData.regeneratorRuntime;
Component({
	/**
	 * 页面的初始数据
	 */
	data: configData.dataConfig,
	behaviors: [modifybehavior],

	methods: {
		/**
		 * 生命周期函数--监听页面加载
		 */
		onLoad: function(options) {
			console.log(options)
			wx.showLoading({
				title: "加载...",
				mask: true,
			})
			this.GetAllScreenItems();
			this.GetAllHospital();
			this.GetScreenResultBy(options.scid, options.leadid);
			this.GetScreenCustomerBy(options.scid, options.leadid);
			this.setData({
				screentype: this.options.screentype,
				screentemplatetype: options.screentemplatetype,
				screenId: options.scid,
				['reservation.ownerId']: this.options.screenownerid,
				['reservation.userid']: app.globalData.userInfo.userid

			});
		},


		//姓名
		nameChange: function(e) {
			this.setData({
				['lead.lastname']: e.detail
			});
		},

		onCamera: function() {
			wx.navigateTo({
				url: "/pages/camera/camera"
			});
		},
		setPersonIdCard: function(idCard) {

			let {
				birthDate,
				gender,
				address,
				nationality,
				name,
				idNumber
			} = idCard;

			let idCardInfo = {
				name: {
					text: name
				},
				gender: {
					text: gender
				},
				address: {
					text: address
				},
				nationality: {
					text: nationality
				},
				id: {
					text: idNumber
				},
				sex: gender
			};

			debugger;
			let birthYear = parseInt(birthDate.substring(0, 4));
			let currYear = new Date().getFullYear();
			let age = currYear - birthYear;
			let new_gender = (gender == "女" ? 1 : 0) + 1;

			let leadEntity = this.data.lead;
			leadEntity.lastname = name;
			leadEntity.new_gender = new_gender;
			leadEntity.new_age = age;
			leadEntity.address1_name = address;
			leadEntity.new_citizenid = idNumber;
			this.setData({
				idCardInfo: idCardInfo,
				age: age ? age : "",
				lead: leadEntity,
				['reservation.new_gender']: new_gender,
				['propageanda.new_gender']: new_gender
			})

		},

		//扫描身份证
		scanSuccess: function(e) {
			if (e.detail) {
				this.setData({
					['lead.new_citizenid']: e.detail.id,
					['lead.lastname']: e.detail.name,
					['lead.new_gender']: e.detail.sex,
					['lead.new_birthdate']: e.detail.birthday,
					['lead.address1_name']: e.detail.homePlace,
				});
			}
		},

		onNameBlur: function(e) {
			let scid = this.data.screenId;
			var that = this;
			screencustomerservice.GetSameNameQuantity(scid, e.detail.value).then(function(res) {
				console.log(res.data);
				that.setData({
					IsShowtip: true,
					samenameqty: "+" + res.data
				})
			});
		},
		//性别
		genderChange: function(e) {
			//console.log()	
			this.setData({
				['lead.new_gender']: e.detail.index + 1
			});
		},
		//年龄
		ageChange: function(e) {
			this.setData({
				['lead.new_age']: e.detail
			});
		},
		//医保类型
		insuranceTypeChange: function(e) {
			//debugger
			this.setData({
				insuranceTypeIndex: e.detail.value,
			});
			if (e.detail.value != 0) {
				var new_insurancetype = this.data.insuranceType[e.detail.value].id;
				this.setData({
					['lead.new_insurancetype']: new_insurancetype,
					['reservation.new_insurancetype']: new_insurancetype,
				})
			}
		},
		//筛查项目
		screenItemChange: function(e) {
			this.setData({
				screenitemIndex: e.detail.value
			});
			if (e.detail.value != 0) {
				// debugger
				var new_screenitemId = this.data.screenitem[e.detail.value].new_screenitemId;
				this.setData({
					['reservation.new_new_screenitem']: new_screenitemId,
					['sccustomer.new_scitemid']: new_screenitemId
				});
			}
		},
		//手机号码
		phoneChange: function(e) {
			this.setData({
				['lead.address1_telephone1']: e.detail
			});
		},
		//手机号码
		phone1Change: function(e) {
			this.setData({
				['lead.new_mobile']: e.detail
			});
		},
		//固定电话
		telphoneChange: function(e) {
			this.setData({
				['lead.telephone2']: e.detail
			});
		},
		//固定电话2
		telphone1Change: function(e) {
			this.setData({
				['lead.address1_telephone2']: e.detail
			});
		},
		//病种
		diseaseChange: function(e) {
			var new_disease = this.data.diseaseArray[e.detail.value].id
			this.setData({
				diseaseIndex: e.detail.value,
				['lead.new_disease']: new_disease
			});
		},
		//家庭住址
		addressChange: function(e) {
			this.setData({
				['lead.address1_name']: e.detail
			});
		},
		//身份证号
		citizenidChange: function(e) {
			this.setData({
				['lead.new_citizenid']: e.detail
			});
			var idcard_patter =
				/^[1-9][0-9]{5}([1][9][0-9]{2}|[2][0][0|1][0-9])([0][1-9]|[1][0|1|2])([0][1-9]|[1|2][0-9]|[3][0|1])[0-9]{3}([0-9]|[X])$/;
			var idnum = e.detail;
			if (idcard_patter.test(idnum)) {
				var born = idnum.substring(6, 10) + "-" + idnum.substring(10, 12) + "-" + idnum.substring(
					12, 14);
				var birthYear = parseInt(idnum.substring(6, 10));
				var currYear = new Date().getFullYear();
				var age = currYear - birthYear;

				this.setData({
					['lead.new_age']: age,
					['lead.new_birthdate']: born,
				})
			}
		},
		idCardBlur: function(e) {
			var idnum = e.detail.value;
			var sex = idnum.substring(idnum.length - 2, idnum.length - 1);
			var new_gender = 1;
			if (sex % 2 > 0) { //奇数
				new_gender = 1;
			} else {
				new_gender = 2;
			}
			this.setData({
				['lead.new_gender']: new_gender
			});
		},
		//医保卡号码
		insuranceidChange: function(e) {
			this.setData({
				['lead.new_insuranceid']: e.detail
			});
		},
		//裸眼视力 右眼
		nakedEyeRight: function() {
			this.setData({
				optionShow: true,
				selectType: 1
			});
		},
		//裸眼视力 左眼
		nakedEyeLeft: function() {
			this.setData({
				optionShow: true,
				selectType: 2
			});
		},
		//右眼 手术情况
		nakedEyeRightChange: function(e) {
			console.log(e);
			if (e.detail.index == 0) {
				this.setData({
					['nakedEyeRightRes.new_result']: 'SC0000000095'
				})
			} else {
				this.setData({
					['nakedEyeRightRes.new_result']: 'SC0000000094'
				})
			}
		},
		//左眼 手术情况
		nakedEyeLeftChange: function(e) {
			if (e.detail.index == 0) {
				this.setData({
					['nakedEyeLeftRes.new_result']: 'SC0000000092'
				})
			} else {
				this.setData({
					['nakedEyeLeftRes.new_result']: 'SC0000000093'
				})
			}
		},
		//矫正视力 右眼
		correctRight: function() {
			this.setData({
				optionShow: true,
				selectType: 3
			})
		},
		//矫正视力 左眼
		correctLeft: function() {
			this.setData({
				optionShow: true,
				selectType: 4
			})
		},
		//全身疾病史
		checkboxonChange: function(e) {
			this.setData({
				result: e.detail
			})
		},
		//眼科初步判断
		onChange: function(e) {
			if (e.currentTarget.id == "cataractRight") {
				var result = scResult.getCataractRes(e.detail.index);
				this.setData({
					['cataractRight.active']: e.detail.index,
					['cataractRight.new_result']: result
				});
			} else if (e.currentTarget.id == "cataractLeft") {
				var result = scResult.getCataractRes(e.detail.index);
				this.setData({
					['cataractLeft.active']: e.detail.index,
					['cataractLeft.new_result']: result
				})
				//白内障（左眼）
			} else if (e.currentTarget.id == "pterygiumRight") {
				var result = scResult.getPterygiumRes(e.detail.index);
				this.setData({
					['pterygiumRight.active']: e.detail.index,
					['pterygiumRight.new_result']: result,
				})
				//翼状胬肉（右眼）
			} else if (e.currentTarget.id == "pterygiumLeft") {
				var result = scResult.getPterygiumRes(e.detail.index);
				this.setData({
					['pterygiumLeft.active']: e.detail.index,
					['pterygiumLeft.new_result']: result,
				})
				//翼状胬肉（左眼）
			} else if (e.currentTarget.id == "lacrimalObstruction") {
				var result = scResult.getRes(e.detail.index);
				this.setData({
					['lacrimalObstruction.active']: e.detail.index,
					['lacrimalObstruction.new_result']: result,
				})
				//泪道阻塞
			} else if (e.currentTarget.id == "trichiasis") {
				var result = scResult.getRes(e.detail.index);
				this.setData({
					['trichiasis.active']: e.detail.index,
					['trichiasis.new_result']: result,
				})
				//脸内翻（倒睫）
			} else if (e.currentTarget.id == "conjunctivitis") {
				var result = scResult.getRes(e.detail.index);
				this.setData({
					['conjunctivitis.active']: e.detail.index,
					['conjunctivitis.new_result']: result,
				})
				//结膜炎
			} else if (e.currentTarget.id == "ametropia") {
				var result = scResult.getRes(e.detail.index);
				this.setData({
					['ametropia.active']: e.detail.index,
					['ametropia.new_result']: result,
				})
				//屈光不正
			} else if (e.currentTarget.id == "fundusDiseases") {
				var result = scResult.getRes(e.detail.index);
				this.setData({
					['fundusDiseases.active']: e.detail.index,
					['fundusDiseases.new_result']: result,
				})
				//眼底疾病
			}
		},
		//描述
		descChange: function(e) {
			this.setData({
				['descriptions.new_result']: e.detail
			})
		},
		//建议
		adviseChange: function(e) {
			this.setData({
				['advise.new_result']: e.detail
			})
		},
		//是否跟进
		followUpChange: function(e) {
			//console.log(e);
			if (e.detail.index == 0) {
				this.setData({
					['propageanda.new_isfollowself']: 1
				})
			} else if (e.detail.index == 1) {
				this.setData({
					['propageanda.new_isfollowself']: 0
				})
			}
		},

		// reservationonChange: function (e) {
		//   if (e.detail.index == 0) {
		//     let userinfo = app.globalData.userInfo;
		//     var hospitalindex = this.getPickerValue(this.data.hospitalList, 'siteId', userinfo.siteid);
		//     var siteId = this.data.hospitalList[hospitalindex].siteId;
		//     this.setData({
		//       reservationShow: true,
		//       hospitalindex: hospitalindex,
		//       ['reservation.new_hospital']: siteId,
		//       ['reservation.new_reservationdate']: this.data.appointmenttothehospitaldate,
		//       ['reservation.new_contnt']: this.data.itemData[this.data.itemindex].id,
		//       iSreservation: true,
		//       ['propageanda.new_isorder']: true,
		//       ['leadEntity.new_reservation']: true
		//     });
		//     this.GetDepartmentsByHospID(siteId);
		//   } else {
		//     this.setData({
		//       reservationShow: false,
		//       iSreservation: false,
		//       ['propageanda.new_isorder']: false,
		//       ['leadEntity.new_reservation']: false
		//     })
		//   }
		// },

		//是否预约
		reservationonChange: async function(e) {
			if (e.detail.index == 0) {
				let userinfo = app.globalData.userInfo;
				var hindex = this.GetPickerValue(this.data.hospitalList, userinfo.siteid);

				var siteId = this.data.hospitalList[hindex].siteId;

				this.setData({
					reservationShow: true,
					iSreservation: e.detail.index,
					hospitalindex: hindex,
					['reservation.new_hospital']: siteId,
					['reservation.new_reservationdate']: util.frmatDate(new Date()),
					['reservation.new_contnt']: this.data.itemData[this.data.itemindex].id,
				});
				// debugger
				await this.GetDempartmentByHospital(siteId);
				if (this.data.departmentList.length > 0) {
					var new_department = this.data.departmentList[0].new_departmentId;
					this.setData({
						['reservation.new_department']: new_department
					});
				}
			} else {
				this.setData({
					reservationShow: false,
					iSreservation: e.detail.index,
				})
			}
		},
		//预约日期
		dateChange: function(e) {
			this.setData({
				['reservation.new_reservationdate']: e.detail.value
			})
		},
		//医院
		changeHospital: async function(e) {
			var new_hospital = this.data.hospitalList[e.detail.value].siteId;
			this.setData({
				hospitalindex: e.detail.value,
				['reservation.new_hospital']: new_hospital
			})
			await this.GetDempartmentByHospital(new_hospital);
			// debugger
			if (this.data.departmentList.length > 0) {
				//console.log(this.data.officeArray);
				var departmentIndex = this.data.departmentIndex;
				var new_department = this.data.departmentList[0].new_departmentId
				this.setData({
					['reservation.new_department']: new_department
				});
			}
		},
		//科室
		bindOfficeChange: function(e) {
			var new_department = this.data.departmentList[e.detail.value].new_departmentId;
			this.setData({
				departmentIndex: e.detail.value,
				['reservation.new_department']: new_department
			});
		},

		//项目
		bindItemChange: function(e) {
			this.setData({
				itemindex: e.detail.value,
				['reservation.new_contnt']: this.data.itemData[e.detail.value].id
			})
		},

		//清空按钮
		onClear: function() {
			if (this.data.selectType == 1) {
				this.setData({
					nakedEyeRightText: '请填写',
					nakedEyeRightId: 0
				});
			} else if (this.data.selectType == 2) {
				this.setData({
					nakedEyeLeftText: '请填写',
					nakedEyeLeftId: 0
				});
			} else if (this.data.selectType == 3) {
				this.setData({
					correctRightText: '请选择',
					correctRightId: 0
				});
			} else if (this.data.selectType == 4) {
				this.setData({
					correctLeftText: '请选择',
					correctLeftId: 0
				});
			}
			this.setData({
				optionShow: false
			});
		},
		//选择结果
		onSelect: function(e) {
			if (this.data.selectType == 1) {
				this.setData({
					nakedEyeRightText: e.currentTarget.dataset.name,
					nakedEyeRightId: e.currentTarget.id,
					['nakedEyeRight.new_result']: e.currentTarget.dataset.name
				});
			} else if (this.data.selectType == 2) {
				this.setData({
					nakedEyeLeftText: e.currentTarget.dataset.name,
					nakedEyeLeftId: e.currentTarget.id,
					['nakedEyeLeft.new_result']: e.currentTarget.dataset.name
				});
			} else if (this.data.selectType == 3) {
				this.setData({
					correctRightText: e.currentTarget.dataset.name,
					correctRightId: e.currentTarget.id,
					['correctRight.new_result']: e.currentTarget.dataset.name
				});
			} else if (this.data.selectType == 4) {
				this.setData({
					correctLeftText: e.currentTarget.dataset.name,
					correctLeftId: e.currentTarget.id,
					['correctLeft.new_result']: e.currentTarget.dataset.name
				});
			}
			this.setData({
				optionShow: false
			});
		},
		onClose: function() {
			this.setData({
				optionShow: false
			})
		},
		//获取下标
		GetPickerValue: function(targetObj, id) {
			for (let index in targetObj) {
				if (targetObj[index].siteId == id) {
					return index
				}
			}
		},
		//打开建议
		onClickIcon: function(e) {
			this.setData({
				adviseshow: true
			})
			//console.log(e);
		},
		//关闭建议
		adviseonClose: function() {
			this.setData({
				adviseshow: false
			})
		},
		//选择建议
		adviseonSelect: function(e) {
			this.setData({
				adviseshow: false,
				['advise.new_result']: e.detail.name
			})
		},
		//备注
		remarkChange: function(e) {
			this.setData({
				['lead.description']: e.detail,
				['reservation.new_remark']: e.detail
			})
		},

		//修改数据
		modResult: function(e) {
			var scobj = {};
			var that = this;
			var lead = that.data.lead;
			if (this.data.screentype == '100000000') { //社区
				lead.new_patientsource = 3;
			} else if (this.data.screentype == '100000001') { //中小学校园
				lead.new_patientsource = 7;
			} else if (this.data.screentype == '100000002') { //大学校园
				lead.new_patientsource = 8;
			} else if (this.data.screentype == '100000003') { //大客户
				lead.new_patientsource = 6;
			}
			var scResults = that.SetResultToArray();
			var reservation = that.data.reservation;
			var customer = that.data.sccustomer;
			if (this.data.iSreservation == 0) {
				scobj.reservation = reservation;
			}
			scobj.lead = lead;
			scobj.customer = customer;
			scobj.CreateResults = scResults;
			console.log(scobj);
			//console.log(scobj.reservation);
			var mobilereg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
			var idreg =
				/^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$|^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/

			//var a = this.data.idCardInfo.name;
			if (lead.lastname.replace(/\s+/g, '') == '') {
				wx.showToast({
					title: '请输入姓名',
					icon: 'none',
					duration: 2000
				});
				return false;
			}

			if (!lead.new_disease) {
				wx.showToast({
					title: '请选择病种',
					icon: 'none',
					duration: 2000
				});
				return false;
			}

			if (lead.new_age != '') {
				if (lead.new_age > 150) {
					wx.showToast({
						title: '请填写正确的年龄',
						icon: 'none',
						duration: 1500
					})
					return false;
				}
			}
			//idCardInfo.id
			if (lead.address1_telephone1) {
				if (!mobilereg.test(lead.address1_telephone1)) {
					wx.showToast({
						title: '请填写正确的手机号码',
						icon: 'none',
						duration: 1500
					})
					return false;
				}
			}

			if (lead.new_mobile) {
				if (!mobilereg.test(lead.new_mobile)) {
					wx.showToast({
						title: '请填写正确的手机号码2',
						icon: 'none',
						duration: 1500
					})
					return false;
				}
			}
			if (lead.new_citizenid) {
				if (!idreg.test(lead.new_citizenid)) {
					wx.showToast({
						title: '请填写正确的身份证号码',
						icon: 'none',
						duration: 1500
					})
					return false;
				}
			}
			if (this.data.reservationShow) {
				if (this.data.itemindex == 0) {
					wx.showToast({
						title: '项目不能为空!',
						duration: 1500,
						icon: 'none'
					})
					return false;
				}

			}
			this.setData({
				IsShowtip: false
			});
			this.UpdataSQSC(scobj);
		},

		/**
		 * 生命周期函数--监听页面初次渲染完成
		 */
		onReady: function() {

		},

		/**
		 * 生命周期函数--监听页面显示
		 */
		onShow: function() {

		},

		/**
		 * 生命周期函数--监听页面隐藏
		 */
		onHide: function() {

		},

		/**
		 * 生命周期函数--监听页面卸载
		 */
		onUnload: function() {

		},

		/**
		 * 页面相关事件处理函数--监听用户下拉动作
		 */
		onPullDownRefresh: function() {

		},

		/**
		 * 页面上拉触底事件的处理函数
		 */
		onReachBottom: function() {

		},

		/**
		 * 用户点击右上角分享
		 */
		onShareAppMessage: function() {

		},


	}
})
